package cn.tedu.product.controller;


import cn.tedu.product.base.response.JsonResult;
import cn.tedu.product.base.response.StatusCode;
import cn.tedu.product.mapper.AdminMapper;
import cn.tedu.product.mapper.UserMapper;
import cn.tedu.product.pojo.dto.DeleteUserDTO;
import cn.tedu.product.pojo.dto.UserLoginDTO;
import cn.tedu.product.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
@RestController
@RequestMapping("v1/Admin/")
@Api(tags = "管理员模块")
public class AdminController {
    @Autowired(required = false)
    private AdminMapper adminMapper;
    @Autowired(required = false)
    private UserMapper userMapper;

    @PostMapping("login")
    @ApiOperation(value = "登录")
    public JsonResult login(@RequestBody @Validated UserLoginDTO loginDTO, @ApiIgnore HttpSession session){
        UserVO userVO=userMapper.selectByUname(loginDTO.getUsername());
        if (userVO!=null){
            if (userVO.getPassword().equals(loginDTO.getPassword())){
               if (userVO.getIsAdmin()==1){
                    session.setAttribute("admin",userVO);
                    return JsonResult.ok(" 管理员登录成功！");
                }

            }
            return new JsonResult(StatusCode.PASSWORD_ERROR);
        }
        return new JsonResult(StatusCode.USERNAME_ERROR);
    }

    @PostMapping("deleteUser")
    @ApiOperation(value = "删除用户")
    public JsonResult deleteUser(@RequestBody DeleteUserDTO deleteUserDTO){
        if (deleteUserDTO.getId()!=null){
            adminMapper.deleteUserById(deleteUserDTO.getId());
            return JsonResult.ok("使用ID删除用户成功");
        }
        if (deleteUserDTO.getUsername()!=null){
            adminMapper.deleteUserByUsername(deleteUserDTO.getUsername());
            return JsonResult.ok("使用Username删除用户成功");
        }
        return JsonResult.notok("请给定用户ID或者Username");
    }


    @PostMapping("getAllUser")
    @ApiOperation(value = "获取所有用户")
    public JsonResult selectAllUser(){
        return JsonResult.ok(adminMapper.selectAllUser());
    }


    @PostMapping("logout")
    @ApiOperation(value = "退出登录")
    public JsonResult logout(@ApiIgnore HttpSession session){
        session.removeAttribute("admin");
        return JsonResult.ok();
    }



    @PostMapping("currentUser")
    @ApiOperation(value = "获取当前管理用户")
    public JsonResult currentUser(@ApiIgnore HttpSession session){
        return JsonResult.ok(session.getAttribute("admin"));
    }
}
